package ${bussiPackage}.${entityPackage}.service.impl;

import ${bussiPackage}.${entityPackage}.entity.${entityName};
import ${bussiPackage}.${entityPackage}.mapper.${entityName}Mapper;
import ${bussiPackage}.${entityPackage}.service.I${entityName}Service;
import org.springframework.stereotype.Service;

<#if generate.isTree == "1">
import ${bussiPackage}.${entityPackage}.entity.${entityName}Tree;
import cn.hutool.core.collection.CollectionUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.google.common.collect.Lists;
import org.springframework.stereotype.Service;

import java.util.List;
</#if>

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;

/**
 * @Description: ${geForm.moduleName}
 * @Author: cc-admin
 * @Date:   ${.now?string["yyyy-MM-dd"]}
 * @Version: V1.0.0
 */
@Service
public class ${entityName}ServiceImpl extends ServiceImpl<${entityName}Mapper, ${entityName}> implements I${entityName}Service {

<#if generate.isTree == "1">
	@Override
	public List<${entityName}Tree> queryTreeList(QueryWrapper<${entityName}> queryWrapper) {
		List<${entityName}> ${entityName?uncap_first}List = baseMapper.selectList(queryWrapper);
		//规定根节点是0
		return renderTree(${entityName?uncap_first}List, "0");
	}

	@Override
	public void removeNodeById(String id) {
		QueryWrapper<${entityName}> queryWrapper = new QueryWrapper<>();
		queryWrapper.eq("${generate.treePid}", id);
		List<${entityName}> ${entityName?uncap_first}List = baseMapper.selectList(queryWrapper);
		if (CollectionUtil.isNotEmpty(${entityName?uncap_first}List)) {
			${entityName?uncap_first}List.forEach(${entityName?uncap_first} -> {
				removeNodeById(${entityName?uncap_first}.getId());
			});
		}
		removeById(id);
	}

	/**
	 * 将列表数据转换为树状结构的
	 * @param ${entityName?uncap_first}List
	 * @param parentId
	 * @return
	 */
	public List<${entityName}Tree> renderTree(List<${entityName}> ${entityName?uncap_first}List, String parentId) {
		List<${entityName}Tree> resultList = Lists.newArrayList();
		for (${entityName} ${entityName?uncap_first} : ${entityName?uncap_first}List) {
			if (parentId.equals(${entityName?uncap_first}.getParentId())) {
				${entityName}Tree ${entityName?uncap_first}Tree = new ${entityName}Tree();
				${entityName?uncap_first}Tree.setId(${entityName?uncap_first}.getId());
				${entityName?uncap_first}Tree.setName(${entityName?uncap_first}.getName());
				resultList.add(${entityName?uncap_first}Tree);
				${entityName?uncap_first}Tree.setChildren(renderTree(${entityName?uncap_first}List, ${entityName?uncap_first}.getId()));
			}
		}
		return resultList;
	}
</#if>
}
